package org.crazyit.album.web;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.util.*;
import java.io.*;

import org.crazyit.album.exception.AlbumException;
import org.crazyit.album.web.base.BaseServlet;
import org.crazyit.album.vo.*;

@WebServlet(urlPatterns = "/turnPage")
public class TurnPageServlet extends BaseServlet {
    public void service(HttpServletRequest request
            , HttpServletResponse response) throws IOException, ServletException {
        String turn = request.getParameter("turn");
        HttpSession session = request.getSession(true);
        String name = (String) session.getAttribute("curUser");
        Object pageObj = session.getAttribute("curPage");

        int curPage = pageObj == null ? 1 : (Integer) pageObj;
        response.setContentType("text/javascript;charset=gbk");
        PrintWriter out = response.getWriter();
        if (curPage == 1 && turn.equals("-1")) {
            out.println("alert('')");
        } else {

            curPage += Integer.parseInt(turn);
            try {
                List<PhotoHolder> photos = as.getPhotoByUser(name, curPage);

                if (photos.size() == 0) {
                    out.println("alert('')");

                } else {
                    curPage -= Integer.parseInt(turn);
                    session.setAttribute("curPage", curPage);
                }
            } catch (AlbumException ex) {
                out.println("alert('" + ex.getMessage() + "')");
            }
        }
    }
}
